package com.sort;

/**
 * 冒泡排序
 * @author dingnate
 */
public class BubbleSort {
	public static void main(String[] args) {
		int[] a = { 49, 38, 65, 97, 176, 213, 227, 49, 78, 34, 12, 164, 11, 18, 1 };
		System.out.println("排序之前：");
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " ");
		}
		System.out.println();
		sort(a);
		System.out.println("排序之后：");
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " ");
		}
	}

	public static void sort(int[] a) {
		int temp = 0;
		for (int i = a.length - 1; i > 0; i--) {
			boolean changed = false;
			for (int j = 0; j < i; ++j) {
				if (a[j + 1] < a[j]) {
					temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
					changed = true;
				}
			}
			// 如果上次冒泡中发先没有元素交换，则认为顺序已经排好，排序终止
			if (!changed){
				break;
			}
		}
	}
}